import OpenGL.GL as gl
import glfw
from .animations.animator import Animator
import time  # 新增导入
import math  # 新增导入
from OpenGL.GLUT import glutInit  # 新增导入

class EazyGUI:
    def __init__(self):
        # 初始化 GUI 库
        import glfw
        if not glfw.init():
            raise Exception("GLFW 初始化失败")
        
        glutInit()  # 初始化 GLUT
        
        self.window = glfw.create_window(800, 600, "EazyGUI 窗口", None, None)
        if not self.window:
            glfw.terminate()
            raise Exception("窗口创建失败")
        
        glfw.make_context_current(self.window)
        self.widgets = []
        self.animator = Animator()
        
    def run(self):
        # 启动 GUI 应用
        previous_time = time.time()
        self.set_callbacks()  # 设置回调
        while not glfw.window_should_close(self.window):
            current_time = time.time()
            delta_time = current_time - previous_time
            previous_time = current_time

            gl.glClear(gl.GL_COLOR_BUFFER_BIT)
            
            for widget in self.widgets:
                widget.render()
            
            self.animator.update(delta_time)
            
            glfw.swap_buffers(self.window)
            glfw.poll_events()

    def add_widget(self, widget):
        # 添加组件并设置其 parent_window
        widget.parent_window = self.window
        self.widgets.append(widget)

    def set_callbacks(self):
        # 设置全局鼠标事件回调
        def cursor_position_callback(window, xpos, ypos):
            for widget in self.widgets:
                widget.update_state(xpos, ypos, None, None)
        
        def mouse_button_callback(window, button, action, mods):
            xpos, ypos = glfw.get_cursor_pos(window)
            for widget in self.widgets:
                widget.update_state(xpos, ypos, button, action)
                if hasattr(widget, 'mouse_button_callback'):
                    widget.mouse_button_callback(window, button, action, mods)
        
        glfw.set_cursor_pos_callback(self.window, cursor_position_callback)
        glfw.set_mouse_button_callback(self.window, mouse_button_callback)